package com.kunya.product.interceptor;


import com.kunya.common.common.ServerResponse;
import com.kunya.common.po.User;
import com.kunya.common.util.CookieUtil;
import com.kunya.common.util.JsonUtil;
import com.kunya.common.util.RedisShardedPoolUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class AuthorityInteceptor implements HandlerInterceptor {
	private static final Logger logger = LoggerFactory.getLogger(AuthorityInteceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		logger.info("preHandle");
		// 获取请求中的方法名
		String methodName ="";
		String className ="";
		if (handler instanceof HandlerMethod) {
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			// 解析handlerMethod
			methodName = handlerMethod.getMethod().getName();
			className = handlerMethod.getBean().getClass().getSimpleName();
		}
		// 解析具体参数
		StringBuffer requesParamtBuffer = new StringBuffer();
		Map paramMap = request.getParameterMap();
		Iterator it = paramMap.entrySet().iterator();
		while (it.hasNext()) {
			Entry entry = (Entry) it.next();
			String mapKey = (String) entry.getKey();
			String mapValue = StringUtils.EMPTY;
			// requst中map为一个string数组
			Object obj = entry.getValue();
			if (obj instanceof String[]) {
				String[] strs = (String[]) obj;
				mapValue = Arrays.toString(strs);
			}
			requesParamtBuffer.append(mapKey).append("=").append(mapValue);

		}
		User user = null;
		// 从cookie中读取loginToken
		String loginToken = CookieUtil.readLoginToken(request);
		// 如果没有token返回强制登录信息
		if (StringUtils.isNotEmpty(loginToken)) {
			String userJsonStr = RedisShardedPoolUtil.get(loginToken);
			// 将数据库中读取的用户信息字符串反序列化为User对象
			user = JsonUtil.string2Obj(userJsonStr, User.class);
		}
		// 如果user为空或者角色不是管理员进入
		if (user == null ) {
			// 设置response相应输出对象
			// 必须重置response不然报异常
 			response.reset();
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/json;charset=UTF-8");

			PrintWriter out = response.getWriter();
			if (user == null) {
				if(StringUtils.equals(className, "ProductManageController")&&StringUtils.equals(methodName, "richtextImgUpload")) {
					Map map=new HashMap<>();
					map.put("msg", "请登录");
					map.put("success", "false");
					out.print(JsonUtil.obj2String(map));
				}else {
				out.print(JsonUtil.obj2String(ServerResponse.createByErrorMessage("用户未登录，拦截器拦截")));}
			} else {
				if(StringUtils.equals(className, "ProductManageController")&&StringUtils.equals(methodName, "richtext_img_upload")) {
					Map map=new HashMap<>();
					map.put("msg", "无权限操作");
					map.put("success", "false");
					out.print(JsonUtil.obj2String(map));
				}else {
				out.print(JsonUtil.obj2String(ServerResponse.createByErrorMessage("用户无权限操作，拦截器拦截")));}
			}
			out.flush();
			out.close();
			return false;
		}

		return true;
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception exception) throws Exception {
		logger.info("afterCompletion");
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
		logger.info("postHandle");
	}

}
